;
(function() {
	//用于存储安全的SOCK连接权限申请信息
	var s_key_cache = {};
	module.exports = {
		prefix: "/notify",
		_init: function(app) {
			notify.init(app);
			notify.on("init", function(conn, data) {
				var s_key = data.s_key;
				if (!s_key) {
					throwCusError("连接参数错误")
				}
				var s_info = s_key_cache[s_key];
				if (!s_info) {
					throwCusError("连接密匙无效")
				} else {
					s_key_cache[s_key] = null; //只有一次有效性，用过后就销毁
				}
				conn.s_key = s_key;
				conn.s_info = s_info;
				var loginer_id = s_info.id;
				(notify.conns[loginer_id] || (notify.conns[loginer_id] = [])).push(conn);
				notify.send(conn, "init-success", conn.id);
			});
			notify.on("close", function(conn) {
				var s_info = s_key_cache[conn.s_key];
				var loginer_id = s_info.id;
				var conSet = notify.conns[loginer_id];
				if (conSet) {
					var index = conSet.indexOf(conn);
					if (index !== -1) {
						conSet.splice(index, 1);
					}
					// if (conSet.length === 0) {
					// 	notify.conns[loginer_id] = null;
					// }
				}
			});
		},
		// get:{
		// 	//管理员获取在线的商家
		// 	"/admin_get_bus":function () {
		// 	},
		// 	//管理员获取在线的用户
		// 	"/admin_get_user":function () {
		// 	},
		// 	//商家获取在自己店铺的用户
		// 	"/bus_get_user":function () {
		// 	}
		// },
		get: {
			"/test/:eventName": function() {
				var eventName = this.params.eventName || "json";
				var user = role.getUser(this);
				var connSet = role.getUserSockSet(user._id);
				if (!connSet) {
					throwCusError("未建立连接")
				}
				notify.send(connSet, eventName, "testStringehehheeh")
				this.body = ResponObj("json", "已经发送");
			}
		},
		post: {
			//通过已经登录的对象权限获取Sock连接的安全key
			"/ask_con_key": function() {
				var body = this.request.body;
				var type = body.type;
				var s_key = type + "_socket_" + (+new Date) + "_" + Math.random();
				switch (type) {
					case "user":
						var loginer = role.getUser(this);
						break;
					case "bus":
						var loginer = role.getBus(this);
						break;
					case "admin":
						var loginer = role.getAdmin(this);
						break;
				}
				if (loginer) {
					//首先要有登录的信息，如果登录了，就可以将sock连接进行缓存，连接者将得到连接密钥s_key
					s_key_cache[s_key] = {
						type: type,
						id: loginer._id
					};
					this.body = ResponObj("json", {
						s_key: s_key
					});
				} else {
					throwCusError("权限不足")
				}
			}
		}
	};
	var notify = require("./notify");
	var role = require("./role");
	var ResponObj = require("../_include/responObj");
}());